package config

import (
	"fmt"
	log "github.com/sirupsen/logrus"
	"os"
	"path/filepath"
	"strings"
	"time"
)

type CustomFormatter struct{}

func (t *CustomFormatter) Format(entry *log.Entry) ([]byte, error) {
	var file string
	var len int
	if entry.Caller != nil {
		file = filepath.Base(entry.Caller.File)
		len = entry.Caller.Line
	}
	output := fmt.Sprintf("[%s][%s][%s:%d][%s]\n", entry.Time.Format("2006-01-02 15:04:05"), strings.ToUpper(entry.Level.String()), file, len, entry.Message)
	if err, ok := entry.Data[log.ErrorKey].(error); ok {
		output += fmt.Sprintf("%+v\n", err)
	}
	return []byte(output), nil
}
func init() {
	//显示文件名和行号
	log.SetReportCaller(true)
	log.SetFormatter(new(CustomFormatter))
	if GetConfig().Log.LogFile != "" {
		applogfile := fmt.Sprintf(GetConfig().Log.LogFile+"/kafka-lag-monitor-%s.log", time.Now().Format("20060102"))
		logFile, err := os.OpenFile(applogfile, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0644)
		if err != nil {
			fmt.Printf("无法创建日志文件:", err)
			return
		}
		log.SetOutput(logFile)
	}
}
